<?php

namespace mpend\modules\team\models;

use Yii;
use common\helpers\Url;
use common\models\workbook\WorkbookMember;

/**
 * 班组记工本加入模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class WorkBookIntrantSearch extends \mpend\models\searchs\WorkBookSearch {

    /**
     * @inheritdoc
     */
    public function buildQuery($alias = 't') {
        $query = static::find();
        if ($alias) {
            $query->alias($alias);
            $alias .= '.';
        }
        $query->active(static::STATUS_ACTIVE);
        $query->andWhere([
            $alias . 'type' => static::TYPE_TEAM,
        ]);
        $query->joinWith([
            'members' => function($q) {
                return $q->alias('members')->active(WorkbookMember::STATUS_ACTIVE);
            }
        ]);
        $userId = Yii::$app->user->id;
        $query->andWhere([
            'and',
            ['!=', $alias . 'user_id', $userId],
            ['members.user_id' => $userId],
            ['members.role_id' => 0],
        ]);
        $query->orderBy([
            $alias . 'created_at' => SORT_DESC,
        ]);
        $query->debug();
        return $query;
    }

    /**
     * 小程序跳转地址
     * @return bool
     */
    public function getMplink() {
        return [
            'type' => 'push',
            'route' => Url::to(['/pages/book/intrant/main', 'id' => $this->id]),
        ];
    }

    public function fields() {
        return [
            'id',
            'title',
            'thumb',
            'description',
            'headman' => function() {
                return $this->headman ? $this->headman : '未设置';
            },
            'type',
            'createdTime',
            'teamwork' => function() {
                return boolval($this->teamwork);
            },
            'memberCount',
            'recommendMembers',
            'actions',
            'worker',
            'mplink',
        ];
    }

}
